import { getRoleApi } from "@/api/role";
import { addUserApi, getUserApi, uploadUserApi } from "@/api/user";
import { DeleteOutlined, EllipsisOutlined, FormOutlined, PlusOutlined, ZoomInOutlined } from "@ant-design/icons";
import { ActionType, ModalForm, ProColumns, ProFormColorPicker, ProFormField, ProFormSelect, ProFormText, ProFormTextArea, ProFormUploadButton, ProFormUploadDragger, ProTable, TableDropdown } from "@ant-design/pro-components";
import { useRequest } from "ahooks";
import { Button, Drawer, Dropdown, Form, Space, Tag, message, Image } from "antd";
import { useEffect, useRef, useState } from "react";
import dayjs from 'dayjs'
import { deleAnno, getAnnoApi, getAnnoTypeApi, uploadAnno } from "@/api/anno";
import { baseURL } from "@/api/request";
import { ChangeAvt } from "@/commpoent/changeAv";
type AvtRefType = {
    target: string;
    changeImg: () => void;
    Imgs:string
}
const AnnoList = () => {
    type GithubIssueItem = getAnno

    const [roleList, setRoleList] = useState<roleTypes[]>([])
    const getRole = useRequest(getAnnoTypeApi, {
        onSuccess: (res) => {
            setRoleList(res.result)
        }
    })
    const AvtpassRef = useRef<AvtRefType>(null)
    const getData = useRequest(getAnnoTypeApi, {
        onSuccess: (res) => {
            console.log(res);

            setDatas(res.result)
        }
    })

    const [datas, setDatas] = useState<annoTypeTypes[]>([])
    const [y, sety] = useState<getAnno>({} as getAnno)
    const [open, setOpen] = useState(false);
    const showDrawer = (data: getAnno) => {
        setOpen(true);
        sety(data)
    };
    const [id,setId] = useState('')
    const [imgs,setImgs] = useState('')
    const onClose = () => {
        setOpen(false);
    };
    const [form] = Form.useForm<any>();
    const columns: ProColumns<GithubIssueItem>[] = [
        {
            dataIndex: 'index',
            valueType: 'indexBorder',
            width: 48,
            title: '序号'
        },
        {
            title: '公告标题',
            dataIndex: 'title',
            copyable: true,
            ellipsis: true,
        },
        {
            disable: true,
            title: '公告类型',
            dataIndex: 'type',
            render: (_, record) => (
                <Space>
                    <Tag color={roleList.find(item => item.value == record.type)?.color}>{roleList.find(item => item.value == record.type)?.label}</Tag>
                </Space>
            ),
        },
        {
            disable: true,
            title: '创建时间',
            dataIndex: 'password',
            search: false,
            render: (_, record) => (
                <Space>
                    {dayjs(record.time).format('YYYY-MM-DD HH:mm:ss')}

                </Space>
            ),
        },
        {
            title: '发布人',
            dataIndex: 'username',
            sorter: true,
            hideInSearch: true,
            render: (_, record) => (
                <Space>
                    <Tag>{record.author?.username}</Tag>
                </Space>
            ),
        },
        {
            title: '操作',
            valueType: 'option',
            key: 'option',
            render: (text, record, _, action) => [
                <div>

                    <Button type="primary" danger shape="circle" icon={<ZoomInOutlined />} size='middle' onClick={() => showDrawer(record)} style={{ marginRight: '10px' }} />
                    <Button type="primary" shape="circle" icon={<DeleteOutlined />} size='middle' onClick={() => { deleAnno(record._id); actionRef.current?.reload() }} style={{ marginRight: '10px' }} />
                    <ModalForm<{
                        title: string,
                        type: number,
                        desc: string,
                        content: string,
                        _id:string
                    }>
                        title="新建角色"
                        trigger={
                            <Button type="primary" danger shape="circle" icon={<FormOutlined />} size='middle' onClick={() => {form.setFieldsValue(record) ;setImgs(record.desc);setId(record._id)}} />
                        }
                        width={300}
                        form={form}
                        onFinish={async (values) => {
                            let res = await uploadAnno({...values,_id:id,desc:imgs})
                            console.log(values);
                            actionRef.current?.reload()
                            message.success('提交成功');
                            return true;
                        }}
                    >
                        <ProFormText width="sm" name="title" label="公告标题" />
                        <ProFormSelect
                            options={datas}
                            name="type"
                            label="公告类型"
                        />
                        <ProFormTextArea name='content' label='公告内容' />
                        <Image
                            
                            width={200}
                            src={imgs?.replace(/public/,baseURL)}
                            onClick={()=>{AvtpassRef.current?.changeImg();
                            }}
                            preview={false}

                        />
                        
                    </ModalForm>

                </div>
            ],
        },
    ];
    const actionRef = useRef<ActionType>();
    return (
        <div>
            <ProTable<GithubIssueItem>
                columns={columns}
                actionRef={actionRef}
                cardBordered
                request={async (params = {}, sort, filter) => {
                    let res = await getAnnoApi(params as getAnno)
                    return {
                        data: res.result as any
                    }
                }}
                editable={{
                    type: 'multiple',
                }}
                columnsState={{
                    persistenceKey: 'pro-table-singe-demos',
                    persistenceType: 'localStorage',
                    onChange(value) {
                        console.log('value: ', value);
                    },
                }}
                rowKey="id"
                search={{
                    labelWidth: 'auto',
                }}
                options={{
                    setting: {
                        listsHeight: 400,
                    },
                }}
                form={{
                    // 由于配置了 transform，提交的参与与定义的不同这里需要转化一下
                    syncToUrl: (values, type) => {
                        if (type === 'get') {
                            return {
                                ...values,
                                created_at: [values.startTime, values.endTime],
                            };
                        }
                        return values;
                    },
                }}
                pagination={{
                    pageSize: 5,
                    onChange: (page) => console.log(page),
                }}
                dateFormatter="string"
                headerTitle="用户创建"

            />
            <Drawer title={y?.title} placement="right" onClose={onClose} open={open}>
                <p>{y?.content}</p>
                <p><Tag color={roleList.find(item => item.value == y?.type)?.color}>{roleList.find(item => item.value == y?.type)?.label}</Tag></p>
                <p>发布人:{y?.author?.username}</p>
                <Image
                    width={200}
                    src={y?.desc?.replace(/public/, baseURL)}
                />
            </Drawer>
            <ChangeAvt ref={AvtpassRef} dianji={setImgs} k={false}/>
        </div>
    );
}

export default AnnoList